<template>
  <div class="edu-page-warp">
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="edu-page-title">权限列表</div>
        <div class="bg-white" style="min-height: 540px;max-height: 640px;overflow: auto;padding:0;">
          <el-tree
            :data="data"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :expand-on-click-node="false"
            check-strictly="true"
            show-checkbox="true"
            check-on-click-node="true"
            highlight-current="true"
            ref="allAuthoritiesTree"
            @check-change="handleCheckChange"
            default-expand-all
          ></el-tree>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="edu-page-title">有效期配置</div>
        <el-card shadow="never">
          <el-form :model="queryForm" ref="studentForm" label-width="80px">
            <el-row>
              <el-col :span="6">
                <el-form-item label="培养层次 : ">
                  <el-select v-model="queryForm.trainingLevel">
                    <el-option
                      v-for="item in options.trainingLevel"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="年级 : ">
                  <el-select v-model="queryForm.grade">
                    <el-option
                      v-for="item in options.grade"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
             
              <el-col :span="6">
                <el-form-item label="学期 : ">
                   <SchoolCalendarSelect v-model="queryForm.calendarId" :filterable="true" @load-done="loadDone"
                    ></SchoolCalendarSelect>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="学院 : ">
                  <el-select v-model="queryForm.faculty" @change="changeFaculty" style="width: 100%">
                    <el-option
                      v-for="item in options.faculty"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="专业 : ">
                  <el-select v-model="queryForm.profession">
                    <el-option
                      v-for="item in options.profession"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="学习形式 : ">
                  <el-select v-model="queryForm.studyType">
                    <el-option
                      v-for="item in options.studyType"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="国际学生 : ">
                  <el-select v-model="queryForm.overseas" style="width: 100%">
                    <el-option
                      v-for="item in options.overseas"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
               <el-form-item label="扩展字段 : ">
                  <el-input v-model="queryForm.content" placeholder="请输入关键字" style="width: 100%;"/>
                </el-form-item>
              </el-col>
            </el-row>
                <div class="float-right">
                  <el-button @click="resetQueryForm">{{$t('message.reset')}}</el-button>
                  <el-button type="primary" @click="onSubmit">{{$t('message.filter')}}</el-button>
                </div>
          </el-form>
        </el-card>
        <div class="edu-page-title mg-top">有效期列表</div>
        <el-card shadow="never">
          <el-row class="border-bottom" style="height:48px;">
            <el-col span="12">
              <span style="line-height: 32px;margin-left:12px;">{{curAuthNameCh}}</span>
              <div class="empty-box"></div>
            </el-col>
            <el-col span="12">
              <div class="float-right"><!-- v-premit-unuse="'auth_code'" -->
                <el-button @click="addEffictiveDate" >{{$t('message.add')}}</el-button>
              </div>
            </el-col>
          </el-row>
          <el-table :data="list" stripe size="mini" class="border-top">
            <el-table-column type="index" label="序号" width="80"></el-table-column>
            <el-table-column prop="faculty" label="学院">
              <template slot-scope="scope">{{!scope.row.faculty? "全部":scope.row.faculty}}</template>
            </el-table-column>
            <el-table-column prop="major" label="专业">
              <template slot-scope="scope">{{!scope.row.major?"全部":scope.row.major}}</template>
            </el-table-column>
            <el-table-column prop="grade" label="年级">
              <template slot-scope="scope">{{scope.row.grade=="-1"?"全部":scope.row.grade}}</template>
            </el-table-column>
            <el-table-column :label="$t('label.schoolTerm')">
          <template slot-scope="scope">{{transCalendar(scope.row.calendarId)}}</template>
        </el-table-column>
            <el-table-column prop="trainingLevel" label="培养层次"></el-table-column>
            <el-table-column prop="formLearning" label="学习形式"></el-table-column>
            <el-table-column label="期限" width="150">
              <template slot-scope="scope">
                <span>{{getDateStr(scope.row.startTime)}} - {{getDateStr(scope.row.endTime)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="editEffictiveDate(scope.row.id)"
                >{{$t('message.edit')}}</el-button>
                <el-button type="text" @click="deleteLine(scope.row.id)">{{$t('message.delete')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增有效期 -->
    <edu-dialog
      :title="title"
      width="600px"
      class="systemDialog"
      :visible.sync="showAddEffictiveDateDialog"
      @close="showAddEffictiveDateDialog = false"
      @confirm="submitCreateForm">
      <el-form :model="effictiveDateForm" ref="effictiveDateForm" label-width="90px" :rules="rules">
        <el-row>
          <el-form-item prop="trainingLevel" label="培养层次 : ">
            <el-select v-model="effictiveDateForm.trainingLevel" style="width: 100%">
              <el-option
                v-for="item in options.trainingLevel"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="年级 : ">
            <el-select v-model="effictiveDateForm.grade" style="width: 100%">
              <el-option
                v-for="item in options.grade"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="学期 : ">
              <SchoolCalendarSelect 
                v-model="effictiveDateForm.calendarId" 
                :filterable="true">
              </SchoolCalendarSelect>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="学院 : ">
            <el-select
              v-model="effictiveDateForm.faculty"
              @change="changeFaculty"
              style="width: 100%">
              <el-option
                v-for="item in options.faculty"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="专业 : ">
            <el-select v-model="effictiveDateForm.major" style="width: 100%">
              <el-option
                v-for="item in options.profession"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="学习形式 : " prop="formLearning">
            <el-select v-model="effictiveDateForm.formLearning" style="width: 100%">
              <el-option
                v-for="item in options.formLearning"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="国际学生 : " prop="overseas">
            <el-select v-model="effictiveDateForm.overseas" style="width: 100%">
              <el-option
                v-for="item in options.overseas"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="开始时间 : " prop="startTime">
            <el-date-picker
              v-model="effictiveDateForm.startTime"
              type="datetime"
              format="yyyy/MM/dd HH:mm"
              align="right"
              placeholder="选择开始日期"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="结束时间 : ">
            <el-date-picker
              v-model="effictiveDateForm.endTime"
              type="datetime"
              format="yyyy/MM/dd HH:mm"
              placeholder="选择结束日期"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row
          style="height: 50px;">
          <el-form-item label="扩展字段:" v-if="isEdit">
            <el-input disabled="true"
              v-model="effictiveDateForm.content"
              type="textarea"
              :rows="2"
              style="width:100%"
              maxlength="255">
              </el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <!-- <span slot="footer">
        <el-button @click="showAddEffictiveDateDialog = false">{{$t('message.cancel')}}</el-button>
        <el-button type="primary" @click="submitCreateForm">{{$t('message.confirm')}}</el-button>
      </span> -->
    </edu-dialog>
  </div>
</template>
<script>
import {
  getAuthorities,
  findAuthPushTimeListPage,
  deleteAuthPushTime,
  addAuthPushTime,
  updateAuthPushTime,
  findAuthPushTimeById
} from "common/src/api/user";
import { queryDic } from "common/src/api/dictionary";
export default {
  name: "GroupList",
  mounted() {
    this.init();
    this.initOptions();
  },
  data() {
    const getGrade = (function() {
      let now = new Date().getFullYear();
      let years = [];
      years.push({
        label: "全部",
        value: -1
      });
      for (let i = 0; i < 6; i++) {
        years.push({
          label: now - i + "",
          value: now - i + ""
        });
      }
      return years;
    })();
    return {
      curAuthNameCh:"",
      title: "",
      //showCheckBox: false,
      data: [],
      isEdit: false,
      defaultProps: {
        children: "children",
        label: "authNameCh"
      },
      showAddEffictiveDateDialog: false,
      effictiveDateForm: {
        trainingLevel: "",
        grade: "",
        faculty: "",
        major: "",
        formLearning: "",
        overseas: "",
        startTime: "",
        endTime: "",
        content: "",
        calendarId: ''
      },
      temp: {
        trainingLevel: "",
        grade: "",
        faculty: "",
        major: "",
        formLearning: "",
        overseas: "",
        startTime: "",
        endTime: ""
      },
      queryForm: {
        trainingLevel: "",
        grade: "",
        faculty: "",
        profession: "",
        pageNum_: 1,
        total: 0,
        pageSize_: 20,
        studyType: "",
        overseas: "",
        authId: "",
        content: "",
        calendarId: '',
      },
      list: [],
      options: {
        trainingLevel: [],
        grade: [],
        faculty: [],
        calendarList: [],
        profession: [],
        formLearning: [],
        calendarId: [],
        overseas: [
          { label: "全部", value: "2" },
          { label: "是", value: "0" },
          { label: "否", value: "1" }
        ]
      },
      curAuthIds: [],
      allAuthorities_origin: [],
      rules: {
        // trainingLevel: [
        //   { required: true, message: "请选择培养层次", trigger: "blur" }
        // ],
        // formLearning: [
        //   { required: true, message: "请选择学习形式", trigger: "blur" }
        // ],
        // overseas: [
        //   { required: true, message: "请选择是否国际学生", trigger: "blur" }
        // ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    loadDone(data){
        this.options.calendarList = data;
      },
    submitCreateForm() {
      this.$refs["effictiveDateForm"].validate(valid => {
        if (valid) {
        /*   if (!this.effictiveDateForm.id) this.createEfffictiveDate();
          else this.updateEffictiveDate(); */
          if (!this.isEdit) this.createEfffictiveDate();
          else this.updateEffictiveDate();
        } else return false;
      });
    },
    updateEffictiveDate() {
      let data = this.transFormData(this.effictiveDateForm);
      updateAuthPushTime(data)
        .then(res => {
          if (res.code == 200) {
            this.$message({ message: "编辑成功", type: "success" });
            this.showAddEffictiveDateDialog = false;
            this.$refs["effictiveDateForm"].resetFields();
          } else throw res.msg;
        })
        .catch(err => {
          this.$message({ message: "编辑失败", type: "error" });
          console.log(err);
        });
    },
    createEfffictiveDate() {
      let data = this.transFormData(this.effictiveDateForm);
      data.auth = Array.from(this.curAuthIds);
      addAuthPushTime(data)
        .then(res => {
          if (res.code == 200) {
            this.$message({ message: "添加成功", type: "success" });
            this.showAddEffictiveDateDialog = false;
            this.$refs["effictiveDateForm"].resetFields();
          } else throw res.msg;
        })
        .catch(err => {
          this.$message({ message: "添加失败", type: "error" });
          console.log(err);
        });
    },
    transFormData(obj) {
      let d = {},
        canChooseAll = ["grade", "faculty", "major"];
      for (let key in obj) {
        let o = obj[key];
        if (canChooseAll.indexOf(key) >= 0 && !o) d[key] = "-1";
        else if (key == "startTime" || key == "endTime")
          if (typeof o === "number") d[key] = new Date(o).getTime();
          else if (o instanceof Date) d[key] = o.getTime();
          else d[key] = 0;
        else d[key] = o;
      }
      return d;
    },
    deleteLine(id) {
      if (!id) return;
      let data = { id: id };
      deleteAuthPushTime(data)
        .then(res => {
          if (res.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.onSubmit();
          } else throw res.msg;
        })
        .catch(err => {
          console.log(err);
        });
    },
    getDateStr(d) {
      if (d != null && d != undefined && d != 0)
        return new Date(d).toLocaleDateString();
      else return " ~";
    },
    addEffictiveDate() {
      this.handleCheckChange();
      if (this.curAuthIds.size == 0) {
        this.$message({ message: "请至少选择一条权限", type: "warning" });
         return;
       }
       this.isEdit=false;
       this.title = "新增";
       this.showAddEffictiveDateDialog = true;
     /*  if (!this.showCheckBox) {
        this.showCheckBox = true;
        this.queryForm.authId = "";
        //this.init();
        this.$message({ message: "请选择左侧权限", type: "success" });
        return;
      } */
     
    },
    editEffictiveDate(id) {
      this.isEdit=true;
      let query = "id=" + id;
      findAuthPushTimeById(query)
        .then(res => {
          if(res.data.calendarId){
            res.data.calendarId = +res.data.calendarId;
          }
          this.effictiveDateForm = transLine(res.data);
          this.changeFaculty(res.data.faculty);
          this.title = "编辑";
          this.showAddEffictiveDateDialog = true;
        })
        .catch(err => {
          console.log(err);
        });

      function transLine(obj) {
        let d = {},
          canChooseAll = ["grade", "faculty", "major"];
        for (let key in obj)
          d[key] = obj[key];
          // if (canChooseAll.indexOf(key) >= 0 && obj[key] == "-1") d[key] = "";
          // else d[key] = obj[key];
        return d;
      }
    },
    /* transPickedAuths() {
      let pickedNodes = this.$refs.allAuthoritiesTree.getCheckedNodes();
      let curPickAuthorities = new Set();
      let that = this;
      pickedNodes.forEach((item, index) => {
        curPickAuthorities.add(item.authId);
        that
          .getAuthorityIdFromNode(item.parentAuthId, that.allAuthorities_origin)
          .forEach((item, i) => {
            curPickAuthorities.add(item);
          });
      });
      this.curAuthIds = curPickAuthorities;
    }, */
    getAuthorityIdFromNode(parentAuthId, originList) {
      let cur = parentAuthId;
      let auths = [];
      while (cur > 0) {
        originList.forEach((item, index) => {
          if (item.authId == cur) {
            auths.push(item.authId);
            cur = item.parentAuthId;
          }
        });
      }
      return auths;
    },
    onSubmit() {
     /*  if (this.showCheckBox) {
        this.showCheckBox = false;
        this.init();
      } */
      console.log(this.queryForm.calendarId);
      
      if (this.queryForm.authId == "") {
        this.$message({
          message: "请先点击选择要查询的权限",
          type: "warning"
        });
        return;
      }
      findAuthPushTimeListPage(this.queryForm)
        .then(res => {
          if (res.code == 200) this.list = res.data.list;
          else throw res.msg;
        })
        .catch(err => {
          console.log(err);
        });
    },
    init() {
      getAuthorities({ roleType: 1 })
        .then(res => {
          if (res.code === 200 && res.data) {
            this.allAuthorities_origin = res.data;
            this.data = this.$utils.listToTree(
              "authId",
              "parentAuthId",
              res.data
            );
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    initOptions() {
      let params = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_PYCC", "X_YX", "X_XXXS","X_XLXQ"]
      };
      queryDic(params)
        .then(res => {
          if (res.code == 200) {
            this.fillSelect(res.data);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    changeFaculty(val) {
      this.options["profession"] = [];
      let params = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["G_ZY"],
        filter: {
          prefix: [val],
          specilaCode: "XY2ZY"
        }
      };
      queryDic(params)
        .then(res => {
          if (res.code == 200) this._fill("profession", res.data.G_ZY);
        })
        .catch(error => {
          console.log(error);
        });
    },
    fillSelect(data) {
      this._fill("trainingLevel", data.X_PYCC);
      this._fill("faculty", data.X_YX);
      this._fill("formLearning", data.X_XXXS);
      this._fill("calendarId", data.X_XLXQ);
    },
    _fill(type, data) {
      this.options[type].push({
        value: "-1",
        label: "全部"
      });
      for (let key in data) {
        this.options[type].push({
          value: key,
          label: String(data[key])
        });
      }
    },
    handleNodeClick(node) {
      this.queryForm.authId = node.authId;
      this.curAuthNameCh = node.authNameCh
      this.onSubmit();
    },
    handleCheckChange(node) {
      let pickedNodes=this.$refs.allAuthoritiesTree.getCheckedNodes();
      let curPickAuthorities = new Set();
      let that = this;
      pickedNodes.forEach((item, index) => {
        curPickAuthorities.add(item.authId);
      });
      this.curAuthIds = curPickAuthorities;
    },
    resetQueryForm() {
      this.queryForm.trainingLevel = "";
      this.queryForm.grade = "";
      this.queryForm.faculty = "";
      this.queryForm.profession = "";
      this.queryForm.studyType = "";
      this.queryForm.overseas = "";
    },
    transCalendar(id) {
      console.log(this.options.calendarList);
      
        for (var i = 1; i < this.options.calendarList.length; i++) {
          let item = this.options.calendarList[i];
          if (id == item.id) {
            return item.fullName;
          }
        }
      }
  },
  watch: {
    showAddEffictiveDateDialog: function(n, o) {
      if (!n) {
        this.effictiveDateForm = this.temp;
        //this.showCheckBox = false;
        this.init();
      }
    }
  }
};
</script>
<style scoped>

</style>